package com.zjl.core.shiro.session;

import com.zjl.core.redis.RedisShiroCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * @author : zhangjl
 * @Description :
 * @Created : 2018-05-31 14:00
 **/
@Component
@Slf4j
public class ShiroSessionDao extends CachingSessionDAO {


    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        RedisShiroCache.hAdd(sessionId.toString(), session);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        if (sessionId == null) {
            log.error("method:doreadSession,shiro sessionid  is null");
            return null;
        }
        return RedisShiroCache.hGet(sessionId.toString());
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        if(session == null || session.getId() == null){
            log.error("Session is null");
            return;
        }
        Serializable sessionId = session.getId();
        RedisShiroCache.hAdd(sessionId.toString(), session);
    }

    @Override
    protected void doUpdate(Session session) {
        update(session);
    }

    @Override
    public void delete(Session session) {
        if(session == null || session.getId() == null){
            log.error("Session is null");
            return;
        }
        RedisShiroCache.hdelete(session.getId().toString());
    }

    @Override
    protected void doDelete(Session session) {
        delete(session);
    }

    @Override
    public Collection<Session> getActiveSessions() {
        List<Session> list = RedisShiroCache.hGetList();
        return list;
    }
}
